<?php
namespace app\api\controller\xilumarket;
use app\common\controller\Api;
use app\common\model\ShortcutReplay as ModelShortcutReplay;

class ShortcutReplay extends Api{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $model;

    public function _initialize() {
        parent::_initialize();
        $this->model = new ModelShortcutReplay;
    }

    /**
     * 快捷回复列表
     *
     * @param int $pagesize
     * @return void
     */
    public function getList($pagesize) {
        $role = input('role');
        if(!$role){
            return $this->error('role参数错误');
        }
        $replays = ModelShortcutReplay::where(['user_id' => $this->auth->id, 'user_role' => $role])->paginate($pagesize);
        $this->success('查询成功', $replays);
    }
    /**
     * 新增快捷回复
     *
     * @return void
     */
    public function add() {
        $params = $this->request->param();
        $role  = $params['role'];
        if(!$role){
            return $this->error('请指定您当前数据的角色');
        }
        if($this->model->where(['user_id' => $this->auth->id, 'user_role' => $role])->count() > 10){
            return $this->error('您的快捷回复已达上限');
        }
        $params['user_id'] = $this->auth->id;
        $params['user_role'] = $role;
        $replay = $this->model->allowField(true)->save($params);
        $this->success('成功添加快捷回复', $replay);
    }

    public function edit($id) {
        $data = $this->model->where(['user_id' => $this->auth->id, 'id' => $id, 'user_role'=>input('role')])->find();
        if(!input('role')){
            return $this->error('请指定您当前数据的角色');
        }
        if (!$data){
            $this->error('未找到该条数据');
        }
        $data->allowField(true)->save($this->request->param());
        $this->success('成功修改快捷回复', $data);
    }

    public function del($id){
        !$this->request->isDelete() && $this->error('权限禁止');
        $data = $this->model->where(['user_id' => $this->auth->id, 'id' => $id])->find();
        if (!$data){
            $this->error('权限禁止');   
        }
        $res = $data->delete();
        $this->success('成功删除快捷回复', $res);
    }
}